<template>
  <el-card :bordered="false" style="width: 99%;margin: +0.5% auto;">
    <div class="app-container" style="margin: -1%;">
      <div class="filter-container">
        字典ID：
        <el-input
          ref="dict_code"
          v-model="temp.dic.dict_code"
          placeholder="请输入字典ID"
          clearable
          class="filter-item"
          style="width: 150px;margin-right: 10px"
        />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchDict">
          查询
        </el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          新增
        </el-button>
        <el-button v-waves class="filter-item" sicon="el-icon-refresh" @click="clearButton">
          重置
        </el-button>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: auto"
        :header-cell-style="{background:'#F8F8F9',color:'#515A6E'}"
      >
        <el-table-column
          label="ID"
          align="center"
          width="70px"
        >
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字典名称" width="90px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.dict_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字典编号" width="80px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.dict_code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template slot-scope="{row}">
            <span>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.updated_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字典类型" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.dict_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260px" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button size="mini" type="primary" icon="el-icon-edit" plain @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button size="mini" icon="el-icon-setting" plain @click="editDictItem(row)">
              字典配置
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" plain @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="query.pagination.total>0"
        :total="query.pagination.total"
        :page.sync="query.pagination.page"
        :limit.sync="query.listQuery.limit"
        @pagination="getList"
      />
      <dict-item-list ref="dictItemList"/>
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" class="el-dialog-style">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp.dic"
          label-position="left"
          label-width="70px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="字典名称" prop="dict_name" label-width="100px">
            <el-input v-model="temp.dic.dict_name" placeholder="请输入字典名称"/>
          </el-form-item>
          <el-form-item label="字典编号" prop="dict_code" label-width="100px">
            <el-input v-model="temp.dic.dict_code" placeholder="请输入字典编号"/>
          </el-form-item>
          <el-form-item label="描述" label-width="100px">
            <el-input v-model="temp.dic.description" placeholder="请输入相关描述"/>
          </el-form-item>
          <el-input v-show="false" v-model="temp.dic.dict_type"/>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            关闭
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import {
  dictPagination,
  fetchPv,
  createDict,
  updateDict,
  deleteDict,
  listDict
} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import DictItemList from '@/views/sys/dict/dictItem'

const dictTypeOptions = [
  {key: '2', dict_type: '数值'},
  {key: '1', dict_type: '字符串'}
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = dictTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: {Pagination, DictItemList},
  directives: {waves},
  filters: {
    statusFilter(dict) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[dict]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      listLoading: true,
      dictTypeOptions,
      query: {
        listQuery: {
          dict_name: '',
          dict_code: '',
          description: '',
          dict_type: '',
          id: null,
          updated_time: null
        },
        pagination: {
          total: 0,
          current: 0,
          page: 0,
          page_info: {
            since_id: 0,
            max_id: 0
          },
          limit: 10
        }
      },
      importanceOptions: [1, 2, 3],
      // lendarTypeOptions,
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      // gencyOptions,
      showReviewer: false,

      temp: {
        dic: {
          id: undefined,
          dict_name: '',
          dict_code: '',
          description: '',
          dict_type: '',
          updated_time: null
        }
      },
      dialogFormVisible: false,
      // dialogItemVisible: true,
      dialogStatus: 'update',
      textMap: {
        update: '编辑字典',
        create: '新增字典'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        dict_code: [{required: true, message: '请填写字典编号', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '请输入整数', trigger: 'blur'}],
        dict_name: [{required: true, message: '请填写字典名称', trigger: 'blur', type: 'string'}]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    clearButton() {
      this.temp.dic.dict_code = ''
      this.getList()
    },
    getList() {
      this.listLoading = true
      dictPagination(this.query).then(response => {
        this.list = response.data.dic
        this.total = response.pagination.total
        this.query.pagination = response.pagination
        this.query.pagination.page = response.pagination.current
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 100)
      })
    },
    searchDict() {
      // this.listLoading = true
      const code_number = this.temp.dic.dict_code
      if (code_number != '') {
        listDict({orm_id: code_number}).then(response => {
          const dictArray = new Array(response.data.dic)
          this.list = dictArray
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 100)
        })
      } else {
        this.getList()
      }
    },

    editDictItem(row) {
      this.temp.dic = Object.assign({}, row) // copy obj
      this.$refs.dictItemList.edit(row)
    },

    resetTemp() {
      this.temp = {
        dic: {
          id: undefined,
          dict_name: '',
          dict_code: '',
          description: '',
          dict_type: '',
          timestamp: new Date()
        }
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.author = 'admin'
          this.temp.dic.dict_type = 1
          createDict(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.temp.dic.dict_code = ''
            this.$notify({
              message: '创建字典成功！',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.dic = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateDict({dict: tempData.dic}).then(() => {
            this.dialogFormVisible = false
            this.temp.dic.dict_code = ''
            this.$notify({
              message: '更新字典成功！',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将删除该条数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDict({dict_id: row.id}).then(() => {
          this.$notify({
            message: '删除字典成功！',
            type: 'success',
            duration: 2000
          })
          const totalPage = Math.ceil((this.total - 1) / 10)
          this.query.pagination.page = this.query.pagination.page > totalPage ? totalPage : this.query.pagination.page
          this.query.pagination.page = this.query.pagination.page < 1 ? 1 : this.query.pagination.page
          this.getList()
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消字典删除'
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
    // getSortClass: function(key) {
    //   const sort = this.query.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>
<style>
.el-dialog-style .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}

.el-drawer-style .el-drawer__header {
  border-bottom: 1px solid #e8eaec;
}

/*.table-page-search-wrapper {*/
/*  margin-top: -16px;*/
/*  margin-bottom: 16px;*/
/*}*/
/*.table-page-search-submitButtons {*/
/*  display: block;*/
/*  margin-bottom: 24px;*/
/*  white-space: nowrap;*/
/*}*/
</style>
